import { req, SConnect } from '@/util/request'
import type { Socket } from 'socket.io-client'
import type { Page, PageOprion, ResData } from '@/types/index'
import type { MsgTable } from '@/types/msg'

/**
 * 获取公告
 * @param page 分页参数
 * @param cdn 查询条件
 * @param order 排序
 * @returns
 */
export function getInform(page: PageOprion, cdn: MsgTable, order: any): ResData<Page<MsgTable>> {
  return req.post('/msg/get', {
    page: {
      num: page.num,
      size: page.size
    },
    cdn: {
      title: cdn.title,
      status: cdn.status,
      order
    }
  })
}

const funMap = new Map<string, (...arg: any) => void>()
export function onInform(cbk: (...arg: any) => void) {
  funMap.set('inform', cbk)
}

let socket: Socket | null = null

/**
 * 链接websocket
 */
export function connect() {
  if (socket) {
    socket.close()
  }
  socket = SConnect()
  funMap.forEach((f, k) => {
    socket?.on(k, f)
  })
}

/**
 *
 * @param ids 需要删除的id
 * @returns
 */
export function delMsg(ids: number[]): ResData<any> {
  return req.post('/msg/del', ids)
}

/**
 * 发送消息
 * @param data 消息
 * @returns
 */
export function sendMsg(data: MsgTable): ResData<any> {
  return req.post('/msg/send/inform', data)
}

/**
 * 下架公告
 * @param id 公告id
 * @returns
 */
export function soldOutMsg(ids: number[]): ResData<any> {
  return req.put(`/msg/sold_out`, { ids })
}
